package com.knife.redis.convert;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.knife.redis.constants.KnifeRedisConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.lang3.time.FastDateFormat;

import java.io.IOException;
import java.text.ParseException;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.regex.Pattern;

/**
 * <p>
 * 带时区的反序列化
 * </p>
 *
 * @author qingsheng.chen 2018/9/4 星期二 19:01
 */
@Slf4j
public class KnifeDateDeserializer extends JsonDeserializer<Date> implements KnifeRedisConstant {
    private static final FastDateFormat FAST_DATE_FORMAT_TIME = FastDateFormat.getInstance(DATE_FORMAT_TIME_PATTERN);
    private static final FastDateFormat FAST_DATE_FORMAT = FastDateFormat.getInstance(DATE_FORMAT_PATTERN);
    private static final String BASIC_REGEX = "^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$";
    @Override
    public Date deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException {
        try {
            String dateTimeStr = jsonParser.getValueAsString();
            if (Pattern.matches(BASIC_REGEX, dateTimeStr)) {
                return FAST_DATE_FORMAT.parse(dateTimeStr);
            }else {
                return FAST_DATE_FORMAT_TIME.parse(dateTimeStr);
            }
        } catch (ParseException e) {
            log.warn("date format error : {}", ExceptionUtils.getStackTrace(e));
            return null;
        }
    }
}
